import { ArticleDetail, CommentRes } from '@/types/data'
import { RootAction } from '@/types/store'

type InitType = {
  info: ArticleDetail
  comment: CommentRes
  reply: CommentRes
}

const initVal: InitType = {
  info: {} as ArticleDetail, // 文章详情对象
  comment: {} as CommentRes, // 文章评论
  reply: {} as CommentRes, // 某个评论的回复
}

export default function articleReducer(state = initVal, action: RootAction) {
  if (action.type === 'article/set_info') {
    return {
      ...state,
      info: action.payload,
    }
  }

  if (action.type === 'article/set_all_comment') {
    const oldComment = state.comment.results || []
    return {
      ...state,
      // comment: action.payload
      comment: {
        ...action.payload,
        results: [...oldComment, ...action.payload.results], // 追加数据
      },
    }
  }

  if (action.type === 'article/save_new_comment') {
    return {
      ...state,
      comment: {
        ...state.comment,
        results: [action.payload, ...state.comment.results],
      },
    }
  }

  if (action.type === 'article/set_reply_list') {
    const oldReplyList = state.reply.results || []

    return {
      ...state,
      reply: {
        ...action.payload,
        results: [
          ...oldReplyList,
          ...action.payload.results, // 追加数据（一定记得清空）
        ],
      },
    }
  }

  return state
}
